
 <!DOCTYPE HTML>
<html >
<head>
  <meta charset="UTF-8">
  
    <title>spring+redis缓存注解 | Typhoon&#39;s code space</title>
    <meta name="viewport" content="width=device-width, initial-scale=1,user-scalable=no">
    
    <meta name="author" content="typhoon">
    

    
    <meta name="description" content="使用缓存的方式很多,有基于工具类手动操作的,也有基于注解的,各有千秋,接下来将借助spring+redis实现基于注解的缓存使用.">
<meta name="keywords" content="spring redis缓存注解">
<meta property="og:type" content="article">
<meta property="og:title" content="spring+redis缓存注解">
<meta property="og:url" content="http://scorpioaeolus.oschina.io/2017/08/29/spring-redis缓存注解/index.html">
<meta property="og:site_name" content="Typhoon&#39;s code space">
<meta property="og:description" content="使用缓存的方式很多,有基于工具类手动操作的,也有基于注解的,各有千秋,接下来将借助spring+redis实现基于注解的缓存使用.">
<meta property="og:image" content="http://scorpioaeolus.oschina.io/typhoon/2017/08/29/spring-redis缓存注解/1.png">
<meta property="og:image" content="http://scorpioaeolus.oschina.io/typhoon/2017/08/29/spring-redis缓存注解/2.png">
<meta property="og:image" content="http://scorpioaeolus.oschina.io/typhoon/2017/08/29/spring-redis缓存注解/2-1.png">
<meta property="og:image" content="http://scorpioaeolus.oschina.io/typhoon/2017/08/29/spring-redis缓存注解/3.png">
<meta property="og:image" content="http://scorpioaeolus.oschina.io/typhoon/2017/08/29/spring-redis缓存注解/4.png">
<meta property="og:image" content="http://scorpioaeolus.oschina.io/typhoon/2017/08/29/spring-redis缓存注解/5.png">
<meta property="og:updated_time" content="2017-08-29T14:25:55.557Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="spring+redis缓存注解">
<meta name="twitter:description" content="使用缓存的方式很多,有基于工具类手动操作的,也有基于注解的,各有千秋,接下来将借助spring+redis实现基于注解的缓存使用.">
<meta name="twitter:image" content="http://scorpioaeolus.oschina.io/typhoon/2017/08/29/spring-redis缓存注解/1.png">

    
    <link rel="alternative" href="/atom.xml" title="Typhoon&#39;s code space" type="application/atom+xml">
    
    
    <link rel="icon" href="/typhoon/img/java.png">
    
    
    <link rel="apple-touch-icon" href="/typhoon/img/jacman.jpg">
    <link rel="apple-touch-icon-precomposed" href="/typhoon/img/jacman.jpg">
    
    <link rel="stylesheet" href="/typhoon/css/style.css">
</head>

  <body>
    <header>
      
<div>
		
			<div id="imglogo">
				<a href="/typhoon/"><img src="/typhoon/img/java.png" alt="Typhoon&#39;s code space" title="Typhoon&#39;s code space"/></a>
			</div>
			
			<div id="textlogo">
				<h1 class="site-name"><a href="/typhoon/" title="Typhoon&#39;s code space">Typhoon&#39;s code space</a></h1>
				<h2 class="blog-motto"></h2>
			</div>
			<div class="navbar"><a class="navbutton navmobile" href="#" title="Menu">
			</a></div>
			<nav class="animated">
				<ul>
					<ul>
					 
						<li><a href="/typhoon/">主页</a></li>
					
						<li><a href="/typhoon/archives">归档</a></li>
					
						<li><a href="/typhoon/about">关于</a></li>
					
					<li>
 					
					<form class="search" action="//google.com/search" method="get" accept-charset="utf-8">
						<label>Search</label>
						<input type="search" id="search" name="q" autocomplete="off" maxlength="20" placeholder="Search" />
						<input type="hidden" name="q" value="site:scorpioaeolus.oschina.io">
					</form>
					
					</li>
				</ul>
			</nav>			
</div>
    </header>
    <div id="container">
      <div id="main" class="post" itemscope itemprop="blogPost">
  
	<article itemprop="articleBody"> 
		<header class="article-info clearfix">
  <h1 itemprop="name">
    
      <a href="/typhoon/2017/08/29/spring-redis缓存注解/" title="spring+redis缓存注解" itemprop="url">spring+redis缓存注解</a>
  </h1>
  <p class="article-author">By
       
		<a href="/typhoon/about" title="typhoon" target="_blank" itemprop="author">typhoon</a>
		
  <p class="article-time">
    <time datetime="2017-08-29T13:56:24.000Z" itemprop="datePublished"> Published 2017-08-29</time>
    
  </p>
</header>
	<div class="article-content">
		
		<div id="toc" class="toc-article">
			<strong class="toc-title">Contents</strong>
		
			<ol class="toc"><li class="toc-item toc-level-5"><a class="toc-link" href="#一、新建maven项目并添加依赖"><span class="toc-number">1.</span> <span class="toc-text">一、新建maven项目并添加依赖</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#二、添加基本配置文件"><span class="toc-number">2.</span> <span class="toc-text">二、添加基本配置文件</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#三、编写业务接口及实现"><span class="toc-number">3.</span> <span class="toc-text">三、编写业务接口及实现</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#四、编写单元测试"><span class="toc-number">4.</span> <span class="toc-text">四、编写单元测试</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#总结"><span class="toc-number">5.</span> <span class="toc-text">总结:</span></a></li></ol>
		
		</div>
		
		<pre><code>使用缓存的方式很多,有基于工具类手动操作的,也有基于注解的,各有千秋,接下来将借助spring+redis实现基于注解的缓存使用.
</code></pre><a id="more"></a>
<h5 id="一、新建maven项目并添加依赖"><a href="#一、新建maven项目并添加依赖" class="headerlink" title="一、新建maven项目并添加依赖"></a>一、新建maven项目并添加依赖</h5><pre><code>新建一个简单的maven项目,引入spring最简依赖以及mysql驱动和redis客户端等依赖:
</code></pre><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div></pre></td><td class="code"><pre><div class="line">&lt;!-- mysql驱动 --&gt;</div><div class="line">&lt;dependency&gt;</div><div class="line">	&lt;groupId&gt;mysql&lt;/groupId&gt;</div><div class="line">	&lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt;</div><div class="line">	&lt;version&gt;5.1.41&lt;/version&gt;</div><div class="line">&lt;/dependency&gt;</div><div class="line">&lt;!-- spring-jdbc操作数据库 --&gt;</div><div class="line">&lt;dependency&gt;</div><div class="line">	&lt;groupId&gt;org.springframework&lt;/groupId&gt;</div><div class="line">	&lt;artifactId&gt;spring-jdbc&lt;/artifactId&gt;</div><div class="line">	&lt;version&gt;4.3.7.RELEASE&lt;/version&gt;</div><div class="line">&lt;/dependency&gt;</div><div class="line">&lt;!-- 阿里开源数据库连接池 --&gt;</div><div class="line">&lt;dependency&gt;</div><div class="line">	&lt;groupId&gt;com.alibaba&lt;/groupId&gt;</div><div class="line">	&lt;artifactId&gt;druid&lt;/artifactId&gt;</div><div class="line">	&lt;version&gt;1.1.2&lt;/version&gt;</div><div class="line">&lt;/dependency&gt;</div><div class="line">&lt;!-- spring操作redis依赖 --&gt;</div><div class="line">&lt;dependency&gt;</div><div class="line">	&lt;groupId&gt;org.springframework.data&lt;/groupId&gt;</div><div class="line">	&lt;artifactId&gt;spring-data-redis&lt;/artifactId&gt;</div><div class="line">	&lt;version&gt;1.7.6.RELEASE&lt;/version&gt;</div><div class="line">&lt;/dependency&gt;</div><div class="line">&lt;!-- redis客户端 --&gt;</div><div class="line">&lt;dependency&gt;</div><div class="line">	&lt;groupId&gt;redis.clients&lt;/groupId&gt;</div><div class="line">	&lt;artifactId&gt;jedis&lt;/artifactId&gt;</div><div class="line">	&lt;version&gt;2.8.2&lt;/version&gt;</div><div class="line">&lt;/dependency&gt;</div><div class="line">&lt;!-- json格式化工具 --&gt;</div><div class="line">&lt;dependency&gt;</div><div class="line">	&lt;groupId&gt;com.alibaba&lt;/groupId&gt;</div><div class="line">	&lt;artifactId&gt;fastjson&lt;/artifactId&gt;</div><div class="line">	&lt;version&gt;1.2.28&lt;/version&gt;</div><div class="line">&lt;/dependency&gt;</div></pre></td></tr></table></figure>
<h5 id="二、添加基本配置文件"><a href="#二、添加基本配置文件" class="headerlink" title="二、添加基本配置文件"></a>二、添加基本配置文件</h5><img src="/typhoon/2017/08/29/spring-redis缓存注解/1.png" alt="result" title="result">
<pre><code>添加上述三个配置文件,jdbc.properties是mysql连接属性,redis.properties是redis连接属性,spring-root.xml是主配文件,内容分别如下:
</code></pre><p><em>jdbc.properties</em>:<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div></pre></td><td class="code"><pre><div class="line">driverClassName=com.mysql.jdbc.Driver</div><div class="line">url=jdbc:mysql://localhost:3306/test</div><div class="line">username=root</div><div class="line">password=root</div><div class="line">filters=stat</div><div class="line">initialSize=2</div><div class="line">maxActive=300</div><div class="line">maxWait=60000</div><div class="line">timeBetweenEvictionRunsMillis=60000</div><div class="line">minEvictableIdleTimeMillis=300000</div><div class="line">validationQuery=SELECT 1</div><div class="line">testWhileIdle=true</div><div class="line">testOnBorrow=false</div><div class="line">testOnReturn=false</div><div class="line">poolPreparedStatements=false</div><div class="line">maxPoolPreparedStatementPerConnectionSize=200</div></pre></td></tr></table></figure></p>
<p><em>redis.properties:</em><br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line">redis.hostName= 10.10.10.204</div><div class="line">redis.port=7000</div><div class="line">redis.timeout=3000</div><div class="line">redis.maxIdle=10</div><div class="line">redis.maxTotal=300</div><div class="line">redis.minIdle=2</div><div class="line">redis.maxWaitMillis=8000</div><div class="line">redis.testOnBorrow=true</div><div class="line">redis.password=</div></pre></td></tr></table></figure></p>
<p><em>spring-root.xml:</em><br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div></pre></td><td class="code"><pre><div class="line">&lt;!-- 开启注解 --&gt;</div><div class="line">&lt;cache:annotation-driven/&gt;</div><div class="line"></div><div class="line">&lt;!-- 加载属性文件 --&gt;</div><div class="line">&lt;context:property-placeholder location=&quot;classpath:/redis.properties&quot; /&gt;</div><div class="line"></div><div class="line">&lt;!-- 扫描包 --&gt;</div><div class="line">&lt;context:component-scan base-package=&quot;com.typhoon.spring_jdbctemplate&quot;/&gt;</div><div class="line"></div><div class="line">&lt;!-- jedis 配置 --&gt;  </div><div class="line">&lt;bean id=&quot;poolConfig&quot; class=&quot;redis.clients.jedis.JedisPoolConfig&quot;&gt;  </div><div class="line">   &lt;property name=&quot;maxIdle&quot; value=&quot;$&#123;redis.minIdle&#125;&quot; /&gt;  </div><div class="line">   &lt;!--&lt;property name=&quot;maxWaitMillis&quot; value=&quot;$&#123;redis.maxWait&#125;&quot; /&gt;--&gt;  </div><div class="line">   &lt;property name=&quot;testOnBorrow&quot; value=&quot;$&#123;redis.testOnBorrow&#125;&quot; /&gt;  </div><div class="line">&lt;/bean&gt;     	</div><div class="line">&lt;!-- redis服务器中心 --&gt;  </div><div class="line">&lt;bean id=&quot;connectionFactory&quot;  </div><div class="line">   class=&quot;org.springframework.data.redis.connection.jedis.JedisConnectionFactory&quot;&gt;  </div><div class="line">   &lt;property name=&quot;poolConfig&quot; ref=&quot;poolConfig&quot; /&gt;  </div><div class="line">   &lt;property name=&quot;port&quot; value=&quot;$&#123;redis.port&#125;&quot; /&gt;  </div><div class="line">   &lt;property name=&quot;hostName&quot; value=&quot;$&#123;redis.hostName&#125;&quot; /&gt;  </div><div class="line">   &lt;!-- &lt;property name=&quot;password&quot; value=&quot;$&#123;redis.password&#125;&quot; /&gt; --&gt;  </div><div class="line">   &lt;property name=&quot;timeout&quot; value=&quot;$&#123;redis.timeout&#125;&quot;&gt;&lt;/property&gt;  </div><div class="line">&lt;/bean&gt;     </div><div class="line"></div><div class="line">&lt;!-- 配置redisTemplate --&gt;</div><div class="line">&lt;bean id=&quot;redisTemplate&quot; class=&quot;org.springframework.data.redis.core.RedisTemplate&quot;&gt;  </div><div class="line">   &lt;property name=&quot;connectionFactory&quot; ref=&quot;connectionFactory&quot; /&gt;  </div><div class="line">   &lt;property name=&quot;keySerializer&quot;&gt;  </div><div class="line">       &lt;bean  </div><div class="line">           class=&quot;org.springframework.data.redis.serializer.StringRedisSerializer&quot; /&gt;  </div><div class="line">   &lt;/property&gt;  </div><div class="line">   &lt;property name=&quot;valueSerializer&quot;&gt;  </div><div class="line">       &lt;bean  </div><div class="line">           class=&quot;org.springframework.data.redis.serializer.JdkSerializationRedisSerializer&quot; /&gt;  </div><div class="line">   &lt;/property&gt;  </div><div class="line">&lt;/bean&gt;  </div><div class="line">&lt;!-- 配置缓存 --&gt;  </div><div class="line">&lt;bean id=&quot;cacheManager&quot; class=&quot;org.springframework.data.redis.cache.RedisCacheManager&quot;&gt;  </div><div class="line">   &lt;constructor-arg ref=&quot;redisTemplate&quot; /&gt;  </div><div class="line">&lt;/bean&gt;   </div><div class="line"></div><div class="line">&lt;!-- 注入上下文工具类 --&gt;</div><div class="line">&lt;bean class=&quot;com.typhoon.spring_jdbctemplate.util.SpringContextUtil&quot; /&gt;</div></pre></td></tr></table></figure></p>
<h5 id="三、编写业务接口及实现"><a href="#三、编写业务接口及实现" class="headerlink" title="三、编写业务接口及实现"></a>三、编写业务接口及实现</h5><p><em>UserService接口定义:</em><br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div></pre></td><td class="code"><pre><div class="line">package com.typhoon.spring_jdbctemplate.service;</div><div class="line"></div><div class="line">import com.typhoon.spring_jdbctemplate.entity.User;</div><div class="line"></div><div class="line">/**</div><div class="line"> * 用户信息接口</div><div class="line"> * </div><div class="line"> * @author Typhoon</div><div class="line"> * @date 2017-08-29 17:48 Tuesday</div><div class="line"> * @since V1.0</div><div class="line"> */</div><div class="line">public interface UserService &#123;</div><div class="line"></div><div class="line">	User selectById(Long id);</div><div class="line">	</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p><em>接口默认实现:</em><br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div></pre></td><td class="code"><pre><div class="line">package com.typhoon.spring_jdbctemplate.service.impl;</div><div class="line"></div><div class="line">import org.springframework.cache.annotation.Cacheable;</div><div class="line">import org.springframework.stereotype.Service;</div><div class="line"></div><div class="line">import com.typhoon.spring_jdbctemplate.dao.UserDao;</div><div class="line">import com.typhoon.spring_jdbctemplate.entity.User;</div><div class="line">import com.typhoon.spring_jdbctemplate.service.UserService;</div><div class="line"></div><div class="line">@Service(&quot;userService&quot;)</div><div class="line">public class UserServiceImpl implements UserService &#123;</div><div class="line">	</div><div class="line">static UserDao userDao = new UserDao();</div><div class="line"></div><div class="line">@Override</div><div class="line">@Cacheable(value=&quot;testId&quot;,key=&quot;&apos;id_&apos;+#id&quot;)</div><div class="line">//@Cacheable(value=&quot;testId&quot;,keyGenerator = &quot;customKeyGenerator&quot;)</div><div class="line">public User selectById(Long id) &#123;</div><div class="line">	System.out.println(&quot;绕过缓存,DB查询&quot;);</div><div class="line">	return userDao.selectById(id);</div><div class="line">&#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p><em>数据库操作dao层实现:</em><br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div></pre></td><td class="code"><pre><div class="line">package com.typhoon.spring_jdbctemplate.dao;</div><div class="line"></div><div class="line">import java.util.List;</div><div class="line"></div><div class="line">import org.springframework.jdbc.core.BeanPropertyRowMapper;</div><div class="line">import org.springframework.jdbc.core.JdbcTemplate;</div><div class="line"></div><div class="line">import com.typhoon.spring_jdbctemplate.entity.User;</div><div class="line">import com.typhoon.spring_jdbctemplate.util.DataSourceUtils;</div><div class="line"></div><div class="line">/**</div><div class="line"> * 用户操作dao</div><div class="line"> * </div><div class="line"> * @author Typhoon</div><div class="line"> * @date 2017-08-22 15:32 Tuesday</div><div class="line"> * @since V1.3.1</div><div class="line"> */</div><div class="line">public class UserDao &#123;</div><div class="line">/**</div><div class="line"> * 获取jdbcTemplate</div><div class="line"> */</div><div class="line">private JdbcTemplate jdbcTemplate = DataSourceUtils.getJdbcTemplate();</div><div class="line"></div><div class="line">public User selectById(Long id) &#123;</div><div class="line">	List&lt;User&gt; list = jdbcTemplate.query(&quot;  select * from User where id = ? limit 1  &quot;, BeanPropertyRowMapper.newInstance(User.class),id);</div><div class="line">	if(null == list || list.isEmpty()) &#123;</div><div class="line">		return null;</div><div class="line">	&#125;</div><div class="line">	return list.get(0);</div><div class="line">&#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p><em>自定义缓存key生成器:</em><br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div></pre></td><td class="code"><pre><div class="line">package com.typhoon.spring_jdbctemplate.cachekey;</div><div class="line"></div><div class="line">import java.lang.reflect.Method;</div><div class="line"></div><div class="line">import org.springframework.cache.interceptor.KeyGenerator;</div><div class="line">import org.springframework.stereotype.Component;</div><div class="line"></div><div class="line">import com.alibaba.fastjson.JSON;</div><div class="line">import com.typhoon.spring_jdbctemplate.util.MD5Util;</div><div class="line"></div><div class="line">/**</div><div class="line"> * 自定义缓存key生成器</div><div class="line"> * </div><div class="line"> * @author Typhoon</div><div class="line"> * @date 2017-08-29 17:47 Tuesday</div><div class="line"> * @since V1.0 </div><div class="line"> */</div><div class="line">@Component(&quot;customKeyGenerator&quot;)</div><div class="line">public class CustomKeyGenerator implements KeyGenerator &#123;</div><div class="line"></div><div class="line">	@Override</div><div class="line">	public Object generate(Object target, Method method, Object... params) &#123;</div><div class="line">		String jsonstr = JSON.toJSONString(params);</div><div class="line">		return method.getName()+&quot;:&quot;+params.hashCode();</div><div class="line">	&#125;</div><div class="line">&#125;</div><div class="line">    自定义key生成规则尽可能满足不同的参数生成的key不同,一定要满足相同的查询条件生成的key相同,这样我们才可能最大限度的使用缓存</div></pre></td></tr></table></figure></p>
<p><em>分析:</em></p>
<pre><code>我们的缓存注解一般情况下都是写到service层,key的生成方式可以使用SpEL表达式,当然也可是使用我们自己定义的key生成器,特别需要注意的是,@Cacheable中key和keyGenerator属性不能同时存在.
</code></pre><h5 id="四、编写单元测试"><a href="#四、编写单元测试" class="headerlink" title="四、编写单元测试"></a>四、编写单元测试</h5><pre><code>编写一个测试类模拟服务消费方:
</code></pre><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div></pre></td><td class="code"><pre><div class="line">package com.typhoon.spring_jdbctemplate.consumer;</div><div class="line"></div><div class="line">import org.springframework.context.support.ClassPathXmlApplicationContext;</div><div class="line"></div><div class="line">import com.typhoon.spring_jdbctemplate.entity.User;</div><div class="line">import com.typhoon.spring_jdbctemplate.service.UserService;</div><div class="line">import com.typhoon.spring_jdbctemplate.util.SpringContextUtil;</div><div class="line"></div><div class="line">public class RedisCacheConsumer &#123;</div><div class="line"></div><div class="line">@SuppressWarnings(&quot;resource&quot;)</div><div class="line">public static void main(String[] args) &#123;</div><div class="line">	new ClassPathXmlApplicationContext(&quot;spring-root.xml&quot;);</div><div class="line">	</div><div class="line">	UserService userService = SpringContextUtil.getBean(&quot;userService&quot;, UserService.class);</div><div class="line">	User u = userService.selectById(1L);</div><div class="line">	System.out.println(u);</div><div class="line">&#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<pre><code>第一次运行后可以看到如下结果:
</code></pre><img src="/typhoon/2017/08/29/spring-redis缓存注解/2.png" alt="result" title="result">   
<pre><code>很明显,我们第一次调用查询,缓存中数据,直接到DB中读取并返回.接着我们再一次运行程序,可以看到以下结果:
</code></pre><img src="/typhoon/2017/08/29/spring-redis缓存注解/2-1.png" alt="result" title="result"> 
<pre><code>没有打印DB查询中的日志信息,目测应该是走了缓存,为了验证我们的猜测,我们使用redis-cli命令连接redis查看缓存中有没有信息:
</code></pre><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">redis-cli -h 10.10.10.204 -p 7000</div></pre></td></tr></table></figure>
<pre><code>执行如下命令:
</code></pre><img src="/typhoon/2017/08/29/spring-redis缓存注解/3.png" alt="result" title="result">  
<pre><code>执行keys *testId*可以看到我们在@Cachable定义的value=&quot;testId&quot;开头的eky已经存在redis中,使用type命令我们可以看到testId~keys的类型是zset也就是有序集合,也就是所有调用该方法产生的缓存对应的key都会放到改集合中,接着使用zrange命令查看集合中的key:
</code></pre><img src="/typhoon/2017/08/29/spring-redis缓存注解/4.png" alt="result" title="result">   
<pre><code>可以看到结果中已经有了我们使用SpEL表达式生成的key,然后我们获取该key对应的内容:
</code></pre><img src="/typhoon/2017/08/29/spring-redis缓存注解/5.png" alt="result" title="result"> 
<pre><code>根据上述结果,我们得出我们查询出的User对象是以字符串的形式存储到redis中.


上边这种是使用SpEL表达式生成key的方式存储查询缓存,当然我们也可以把注解中的keyGenerator=&quot;customerkeyGenerator&quot;然后删除key属性来生成key的方式存储缓存,此处不做赘述,可以自己尝试一下.
</code></pre><h5 id="总结"><a href="#总结" class="headerlink" title="总结:"></a>总结:</h5><pre><code>通过上述一系列的配置和编码,我们实现了spring+redis实现的基于注解的查询缓存,接下来分析一下其优缺点:
</code></pre><ul>
<li>优点:1)使用简单方便,2)缓存key管理统一    </li>
<li>缺点:1)对于一些特定的场景不够灵活 2)存在缓存穿透、雪崩的问题</li>
</ul>
<p><em>ps</em>:原创不易,多多支持!</p>
  
	</div>
		<footer class="article-footer clearfix">
<div class="article-catetags">

<div class="article-categories">
  <span></span>
  <a class="article-category-link" href="/typhoon/categories/缓存/">缓存</a>
</div>


  <div class="article-tags">
  
  <span></span> <a href="/typhoon/tags/spring-redis缓存注解/">spring redis缓存注解</a>
  </div>

</div>



	<div class="article-share" id="share">
	
	  <div data-url="http://scorpioaeolus.oschina.io/2017/08/29/spring-redis缓存注解/" data-title="spring+redis缓存注解 | Typhoon&#39;s code space" data-tsina="null" class="share clearfix">
	  </div>
	
	</div>


</footer>

   	       
	</article>
	
<nav class="article-nav clearfix">
 
 <div class="prev" >
 <a href="/typhoon/2017/09/17/基于业务的列表比较器/" title="基于业务的列表比较器">
  <strong>上一篇：</strong><br/>
  <span>
  基于业务的列表比较器</span>
</a>
</div>


<div class="next">
<a href="/typhoon/2017/08/28/spring上下文工具类/"  title="spring上下文工具类">
 <strong>下一篇：</strong><br/> 
 <span>spring上下文工具类
</span>
</a>
</div>

</nav>

	


</div>  
      <div class="openaside"><a class="navbutton" href="#" title="Show Sidebar"></a></div>

  <div id="toc" class="toc-aside">
  <strong class="toc-title">Contents</strong>
 
 <ol class="toc"><li class="toc-item toc-level-5"><a class="toc-link" href="#一、新建maven项目并添加依赖"><span class="toc-number">1.</span> <span class="toc-text">一、新建maven项目并添加依赖</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#二、添加基本配置文件"><span class="toc-number">2.</span> <span class="toc-text">二、添加基本配置文件</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#三、编写业务接口及实现"><span class="toc-number">3.</span> <span class="toc-text">三、编写业务接口及实现</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#四、编写单元测试"><span class="toc-number">4.</span> <span class="toc-text">四、编写单元测试</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#总结"><span class="toc-number">5.</span> <span class="toc-text">总结:</span></a></li></ol>
 
  </div>

<div id="asidepart">
<div class="closeaside"><a class="closebutton" href="#" title="Hide Sidebar"></a></div>
<aside class="clearfix">

  


  
<div class="categorieslist">
	<p class="asidetitle">Categories</p>
		<ul>
		
		  
			<li><a href="/typhoon/categories/dubbo/" title="dubbo">dubbo<sup>8</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/java性能优化/" title="java性能优化">java性能优化<sup>17</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/java源码分析/" title="java源码分析">java源码分析<sup>1</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/motan/" title="motan">motan<sup>2</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/spring/" title="spring">spring<sup>11</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/springboot/" title="springboot">springboot<sup>28</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/springmvc/" title="springmvc">springmvc<sup>1</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/容器/" title="容器">容器<sup>1</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/工具/" title="工具">工具<sup>7</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/性能优化/" title="性能优化">性能优化<sup>5</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/架构/" title="架构">架构<sup>8</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/案例分析/" title="案例分析">案例分析<sup>13</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/缓存/" title="缓存">缓存<sup>4</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/设计模式/" title="设计模式">设计模式<sup>3</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/面试题/" title="面试题">面试题<sup>1</sup></a></li>
		  
		
		</ul>
</div>


  
<div class="tagslist">
	<p class="asidetitle">Tags</p>
		<ul class="clearfix">
		
			
				<li><a href="/typhoon/tags/springboot/" title="springboot">springboot<sup>28</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/java性能优化/" title="java性能优化">java性能优化<sup>9</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/限流/" title="限流">限流<sup>3</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/Spring5/" title="Spring5">Spring5<sup>3</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/设计模式/" title="设计模式">设计模式<sup>3</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/案例分析/" title="案例分析">案例分析<sup>2</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/性能优化/" title="性能优化">性能优化<sup>2</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/Spring/" title="Spring">Spring<sup>2</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/dubbo/" title="dubbo">dubbo<sup>2</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/分页/" title="分页">分页<sup>2</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/并发/" title="并发">并发<sup>2</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/异常拦截/" title="异常拦截">异常拦截<sup>1</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/dubbo分布式事务/" title="dubbo分布式事务">dubbo分布式事务<sup>1</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/自带图片/" title="自带图片">自带图片<sup>1</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/svn导出mvn项目/" title="svn导出mvn项目">svn导出mvn项目<sup>1</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/dubbo过滤器/" title="dubbo过滤器">dubbo过滤器<sup>1</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/排序性能对比/" title="排序性能对比">排序性能对比<sup>1</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/ListenableFuture/" title="ListenableFuture">ListenableFuture<sup>1</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/PropertyChangeListener/" title="PropertyChangeListener">PropertyChangeListener<sup>1</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/jdbcTemplate高可用/" title="jdbcTemplate高可用">jdbcTemplate高可用<sup>1</sup></a></li>
			
		
		</ul>
</div>


  <div class="linkslist">
  <p class="asidetitle">Links</p>
    <ul>
        
          <li>
            
            	<a href="https://coderq.com" target="_blank" title="一个面向程序员交流分享的新一代社区">码农圈</a>
            
          </li>
        
          <li>
            
            	<a href="http://wuchong.me" target="_blank" title="Jark&#39;s Blog">Jark&#39;s Blog</a>
            
          </li>
        
    </ul>
</div>

  


  <div class="rsspart">
	<a href="/atom.xml" target="_blank" title="rss">RSS</a>
</div>

  <div class="weiboshow">
  <p class="asidetitle">Weibo</p>
    <iframe width="100%" height="119" class="share_self"  frameborder="0" scrolling="no" src="http://widget.weibo.com/weiboshow/index.php?language=&width=0&height=119&fansRow=2&ptype=1&speed=0&skin=9&isTitle=1&noborder=1&isWeibo=0&isFans=0&uid=null&verifier=b3593ceb&dpc=1"></iframe>
</div>


</aside>
</div>
    </div>
    <footer><div id="footer" >
	
	<div class="line">
		<span></span>
		<div class="author"></div>
	</div>
	
	
	<section class="info">
		<p> Hello ,I&#39;m a java coder. <br/>
			This is my blog,believe it or not.</p>
	</section>
	 
	<div class="social-font" class="clearfix">
		
		
		
		
		
		
		
		
		
		
		<a href="mailto:ScorpioAeolus@163.com" target="_blank" class="icon-email" title="Email Me"></a>
		
	</div>
			
		

		<p class="copyright">
		Powered by <a href="http://hexo.io" target="_blank" title="hexo">hexo</a> and Theme by <a href="https://github.com/wuchong/jacman" target="_blank" title="Jacman">Jacman</a> © 2019 
		
		<a href="/typhoon/about" target="_blank" title="typhoon">typhoon</a>
		
		
		</p>
</div>
</footer>
    <script src="/typhoon/js/jquery-2.0.3.min.js"></script>
<script src="/typhoon/js/jquery.imagesloaded.min.js"></script>
<script src="/typhoon/js/gallery.js"></script>
<script src="/typhoon/js/jquery.qrcode-0.12.0.min.js"></script>

<script type="text/javascript">
$(document).ready(function(){ 
  $('.navbar').click(function(){
    $('header nav').toggleClass('shownav');
  });
  var myWidth = 0;
  function getSize(){
    if( typeof( window.innerWidth ) == 'number' ) {
      myWidth = window.innerWidth;
    } else if( document.documentElement && document.documentElement.clientWidth) {
      myWidth = document.documentElement.clientWidth;
    };
  };
  var m = $('#main'),
      a = $('#asidepart'),
      c = $('.closeaside'),
      o = $('.openaside');
  c.click(function(){
    a.addClass('fadeOut').css('display', 'none');
    o.css('display', 'block').addClass('fadeIn');
    m.addClass('moveMain');
  });
  o.click(function(){
    o.css('display', 'none').removeClass('beforeFadeIn');
    a.css('display', 'block').removeClass('fadeOut').addClass('fadeIn');      
    m.removeClass('moveMain');
  });
  $(window).scroll(function(){
    o.css("top",Math.max(80,260-$(this).scrollTop()));
  });
  
  $(window).resize(function(){
    getSize(); 
    if (myWidth >= 1024) {
      $('header nav').removeClass('shownav');
    }else{
      m.removeClass('moveMain');
      a.css('display', 'block').removeClass('fadeOut');
      o.css('display', 'none');
      
      $('#toc.toc-aside').css('display', 'none');
        
    }
  });
});
</script>

<script type="text/javascript">
$(document).ready(function(){ 
  var ai = $('.article-content>iframe'),
      ae = $('.article-content>embed'),
      t  = $('#toc'),
      ta = $('#toc.toc-aside'),
      o  = $('.openaside'),
      c  = $('.closeaside');
  if(ai.length>0){
    ai.wrap('<div class="video-container" />');
  };
  if(ae.length>0){
   ae.wrap('<div class="video-container" />');
  };
  c.click(function(){
    ta.css('display', 'block').addClass('fadeIn');
  });
  o.click(function(){
    ta.css('display', 'none');
  });
  $(window).scroll(function(){
    ta.css("top",Math.max(140,320-$(this).scrollTop()));
  });
});
</script>


<script type="text/javascript">
$(document).ready(function(){ 
  var $this = $('.share'),
      url = $this.attr('data-url'),
      encodedUrl = encodeURIComponent(url),
      title = $this.attr('data-title'),
      tsina = $this.attr('data-tsina'),
      description = $this.attr('description');
  var html = [
  '<div class="hoverqrcode clearfix"></div>',
  '<a class="overlay" id="qrcode"></a>',
  '<a href="https://www.facebook.com/sharer.php?u=' + encodedUrl + '" class="article-share-facebook" target="_blank" title="Facebook"></a>',
  '<a href="https://twitter.com/intent/tweet?url=' + encodedUrl + '" class="article-share-twitter" target="_blank" title="Twitter"></a>',
  '<a href="#qrcode" class="article-share-qrcode" title="微信"></a>',
  '<a href="http://widget.renren.com/dialog/share?resourceUrl=' + encodedUrl + '&srcUrl=' + encodedUrl + '&title=' + title +'" class="article-share-renren" target="_blank" title="人人"></a>',
  '<a href="http://service.weibo.com/share/share.php?title='+title+'&url='+encodedUrl +'&ralateUid='+ tsina +'&searchPic=true&style=number' +'" class="article-share-weibo" target="_blank" title="微博"></a>',
  '<span title="Share to"></span>'
  ].join('');
  $this.append(html);

  $('.hoverqrcode').hide();

  var myWidth = 0;
  function updatehoverqrcode(){
    if( typeof( window.innerWidth ) == 'number' ) {
      myWidth = window.innerWidth;
    } else if( document.documentElement && document.documentElement.clientWidth) {
      myWidth = document.documentElement.clientWidth;
    };
    var qrsize = myWidth > 1024 ? 200:100;
    var options = {render: 'image', size: qrsize, fill: '#2ca6cb', text: url, radius: 0.5, quiet: 1};
    var p = $('.article-share-qrcode').position();
    $('.hoverqrcode').empty().css('width', qrsize).css('height', qrsize)
                          .css('left', p.left-qrsize/2+20).css('top', p.top-qrsize-10)
                          .qrcode(options);
  };
  $(window).resize(function(){
    $('.hoverqrcode').hide();
  });
  $('.article-share-qrcode').click(function(){
    updatehoverqrcode();
    $('.hoverqrcode').toggle();
  });
  $('.article-share-qrcode').hover(function(){}, function(){
      $('.hoverqrcode').hide();
  });
});   
</script>









<link rel="stylesheet" href="/typhoon/fancybox/jquery.fancybox.css" media="screen" type="text/css">
<script src="/typhoon/fancybox/jquery.fancybox.pack.js"></script>
<script type="text/javascript">
$(document).ready(function(){ 
  $('.article-content').each(function(i){
    $(this).find('img').each(function(){
      if ($(this).parent().hasClass('fancybox')) return;
      var alt = this.alt;
      if (alt) $(this).after('<span class="caption">' + alt + '</span>');
      $(this).wrap('<a href="' + this.src + '" title="' + alt + '" class="fancybox"></a>');
    });
    $(this).find('.fancybox').each(function(){
      $(this).attr('rel', 'article' + i);
    });
  });
  if($.fancybox){
    $('.fancybox').fancybox();
  }
}); 
</script>



<!-- Analytics Begin -->



<script>
var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "//hm.baidu.com/hm.js?e6d1f421bbc9962127a50488f9ed37d1";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script>



<!-- Analytics End -->

<!-- Totop Begin -->

	<div id="totop">
	<a title="Back to Top"><img src="/typhoon/img/scrollup.png"/></a>
	</div>
	<script src="/typhoon/js/totop.js"></script>

<!-- Totop End -->

<!-- MathJax Begin -->
<!-- mathjax config similar to math.stackexchange -->


<!-- MathJax End -->

<!-- Tiny_search Begin -->

<!-- Tiny_search End -->

  </body>
</html>
